import { getOpenFormData, getPreviewFormData } from '@/api/form'
import { handleLinkFormList } from '@/tools/form-list'

const state = {
  formData: {},
  formValue: {}
}

const mutations = {
  SET_DATA: (state, formData) => {
    state.formData = formData
  },
  SET_VALUES: (state, params) => {
    // 已经存在表单比新建表单多个RID,
    // 因为主表字段也在此对象中不可以直接赋值所以要区分新增还是旧的
    if (JSON.stringify(params) !== '{}' && Object.keys(params).indexOf('.RID')== -1) {
      let prefix = Object.keys(params)[0].split('.')[0]
      let key = prefix + '.RID'
      // 新增数据
      if (state.formValue[key]) {
        delete state.formValue[key]
      }
    }

    // 此处解决新获取表达数据时会覆盖已有数据问题
    state.formValue = {
      ...state.formValue,
      ...params
    }

    window.theValues = state.formValue
  },
  UPDATE_VALUE: (state, params) => {
    state.formValue = Object.assign(state.formValue, {
      [params.key]: params.value
    })

    window.theValues = state.formValue
  }
}

const actions = {
  setData({ commit }, formData) {
    commit('SET_DATA', formData)
  },
  getData({ commit }, query) {
    return new Promise((resolve, reject) => {
      let excutor = null
      let params = {}

      if (query.isPreview) {
        const { id } = query
        params = new URLSearchParams()
        params.append('formId', id)
        excutor = getPreviewFormData
      } else if (query.processInstanceId) {
        const { taskId, processInstanceId, openFormType, listName } = query
        params = {
          taskId: taskId || null,
          processInstanceId: processInstanceId || '',
          openFormType: openFormType || 1,
          listName
        }
        excutor = getOpenFormData
      }

      excutor(params).then(data => {
        const formData = handleLinkFormList(data)
        commit('SET_DATA', formData)
        resolve(formData)
      }).catch(err => {
        reject(err)
      })
    })
  },
  updateValue ({ commit }, params) {
    commit('UPDATE_VALUE', params)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
